import { defineStore } from 'pinia';
import { useUserInfoStore } from './user';
import { useToastStore } from './toast';
import { useI18nStore } from './i18n';

import {
  getBigFileList,
  getFileList,
  deleteFile,
  searchFile,
  addShare,
  updateShare,
  deleteShare,
  downloadPoints,
  downloadBigPoints,
  deleteFileLog,
  recoverFile
} from '@/apis/file';
import { uploadFile, uploadBigFile } from '@/apis/upload';
import { FlipDrag } from '@/utils/filpDrag';
import http from '@/utils/http';

export const SORT_TYPE = {
  DATE: 'create_time',
  FILE_NAME: 'name'
};
export const SORT_ORDER = {
  ASC: 'asc',
  DESC: 'desc'
};
let curControlledContainer = null;
let curContainer = null;

const DTDS = {
  image: ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'ico', 'bmp'],
  video: [
    'mp4',
    'avi',
    'wmv',
    'mov',
    'flv',
    '3gp',
    'mkv',
    'mp3',
    'wav',
    'wma',
    'ogg',
    'aac',
    'flac'
  ],
  document: [
    'pdf',
    'doc',
    'docx',
    'xls',
    'xlsx',
    'txt',
    'xmind',
    'ppt',
    'pptx'
  ],
  Other: [
    'zip',
    'rar',
    '7z',
    'apk',
    'ipa',
    'html',
    'css',
    'scss',
    'less',
    'js',
    'ts',
    'jsx',
    'tsx',
    'vue',
    'json'
  ]
};

function getDtd(filename) {
  // 提取文件的后缀
  const extension = filename.split('.').pop().toLowerCase();
  // 判断文件类型
  if (DTDS.image.includes(extension)) {
    return 'image';
  } else if (DTDS.video.includes(extension)) {
    return 'video';
  } else if (DTDS.document.includes(extension)) {
    return 'document';
  } else {
    return 'Other';
  }
}

export const useFileStore = defineStore('file', {
  state: () => {
    return {
      curFolderId: 0,
      curFolderInfo: {},
      curFileInfo: {},
      prevFolders: [],
      curFileList: [],
      curFolderList: [],
      curSortFunc: () => 1,
      curSortType: SORT_TYPE.DATE,
      curSortOrder: SORT_ORDER.ASC,
      curUploadTasks: new Set(),
      isGridironPlan: true,
      curSearchedFileList: [],
      curSearchKeyword: '',
      curShareList: [],
      type: '',
      total: '',
      // 大小文件 1大文件 2小文件
      Type: 1,
      visible: false,
      delFilesList: [],
      CurrentFileType: ''
    };
  },

  actions: {
    setCurrentFileType(type) {
      this.CurrentFileType = type;
    },

    optimizeFunctions: async function (option) {
      try {
        const promiseArr = this.delFilesList
          .map((item) => {
            if (option === 'del') {
              return deleteFile({ id: item.id });
            } else if (option === 'Cancel') {
              return deleteFileLog({ id: item.id });
            } else if (option === 'recover') {
              return recoverFile({ id: item.id });
            }
            return null;
          })
          .filter((promise) => promise !== null);
        await Promise.all(promiseArr);
        this.visible = false;
      } catch (error) {
        console.error('批量删除失败:', error);
      }
    },

    setdelFileList(list) {
      this.delFilesList = list;
    },

    setVisible(vis) {
      if (vis === 1) {
        this.visible = false;
        return;
      }
      this.visible = !this.visible;
    },

    setType(type) {
      this.Type = type;
    },

    setTotal(total) {
      this.total = total;
    },

    // 获取当前文件夹路径
    getPath: function () {
      const list = [...this.prevFolders, this.curFolderInfo];
      list.shift();
      return list.map((item) => item.name).join('/') + '/';
    },

    updateFileList: async function (file) {
      this.curFileList = [];
      this.curFolderList = [];
      if (this.Type === 2) {
        const { data } = await getFileList();
        this.curFileList = data.list.map((item) => {
          return {
            ...item,
            ext: item.name.split('.').pop(),
            create_time: new Date(item.createTime).toLocaleString(),
            isSmall: true,
            dtd: getDtd(item.name)
          };
        });
      } else if (this.Type === 1) {
        const { data } = await getBigFileList({
          prefix: file ? file.path + file.name + '/' : this.getPath(),
          isRubbish: false
        });
        data.list.forEach((item) => {
          if (item.isFolder) {
            let data = {};
            data = {
              ...item,
              type: 'folder',
              folder_id: item.id,
              create_time: new Date(item.createTime).toLocaleString(),
              isSmall: false
            };
            this.curFolderList.push(data);
          } else {
            let data = {};
            data = {
              ...item,
              file_id: item.id,
              ext: item.name.split('.').pop(),
              create_time: new Date(item.createTime).toLocaleString(),
              isSmall: false,
              dtd: getDtd(item.name)
            };
            this.curFileList.push(data);
          }
        });
      } else if (this.Type === 3) {
        const { data } = await getBigFileList({ isOnlyShare: true });
        data.list.forEach((item) => {
          if (item.isFolder) {
            let data = {};
            data = {
              ...item,
              type: 'folder',
              folder_id: item.id,
              create_time: new Date(item.createTime).toLocaleString(),
              isSmall: false
            };
            this.curFolderList.push(data);
          } else {
            let data = {};
            data = {
              ...item,
              file_id: item.id,
              ext: item.name.split('.').pop(),
              create_time: new Date(item.createTime).toLocaleString(),
              isSmall: false,
              dtd: getDtd(item.name)
            };
            this.curFileList.push(data);
          }
        });
      } else if (this.Type === 4) {
        const { data } = await getBigFileList({ isRubbish: true });
        data.list.forEach((item) => {
          if (item.isFolder) {
            let data = {};
            data = {
              ...item,
              type: 'folder',
              folder_id: item.id,
              create_time: new Date(item.createTime).toLocaleString(),
              isSmall: false
            };
            this.curFolderList.push(data);
          } else {
            let data = {};
            data = {
              ...item,
              file_id: item.id,
              ext: item.name.split('.').pop(),
              create_time: new Date(item.createTime).toLocaleString(),
              isSmall: false,
              dtd: getDtd(item.name)
            };
            this.curFileList.push(data);
          }
        });
      } else {
        console.error('未知页面');
      }
      this.switchSortFunc(this.curSortType, this.curSortOrder);
      return true;
    },
    shareFile: async function (data) {
      const res = await addShare(data);
      await this.updateFileList();
      return res;
    },
    deleteShareFile: async function (shareId) {
      await deleteShare({ id: shareId });
      await this.updateFileList();
      this.setCurFileInfo({
        ...this.curFileInfo
      });
      return true;
    },
    updateShareFile: async function (data) {
      await updateShare(data);
      await this.updateFileList();
      return true;
    },
    updateCurSearchedFileList: async function (keyword) {
      const { data } = await searchFile({
        nameLike: keyword
      });
      this.curSearchedFileList = data.list || [];
      return true;
    },
    setSearchedKeyword: async function (keyword) {
      this.curSearchKeyword = keyword;
      await this.updateCurSearchedFileList(keyword);
      return true;
    },
    deleteFile: async function (file) {
      await deleteFile({ id: file.id });
      this.updateFileList();
    },

    deleteFileMove: async function (id) {
      await deleteFileLog({ id });
      this.updateFileList();
    },

    recoverFileMove: async function (id) {
      await recoverFile({ id });
      this.updateFileList();
    },

    setCurFolderId: function (folderId) {
      this.curFolderId = folderId;
    },

    entryFolder: async function (folderId, type = '') {
      this.curFolderId = folderId;
      this.type = type;
      this.setCurFileInfo({});
      if (folderId !== 0) {
        this.prevFolders.push(this.curFolderInfo);
        const folderInfo = this.curFolderList.find(
          (f) => f.folder_id === folderId
        );
        this.setCurFolderInfo(folderInfo);
      } else {
        this.setprevFolders([]);
      }
      await this.updateFileList();
    },
    // 返回上一页
    backToParentFolder: async function () {
      if (this.prevFolders.length === 0) return;
      const prevFolder = this.prevFolders.pop();
      this.setCurFolderInfo(prevFolder);
      this.curFolderId = prevFolder.id;
      this.setCurFileInfo({});
      await this.updateFileList();
    },
    setprevFolders: function (foldersList) {
      this.prevFolders = foldersList;
    },
    setCurFileInfo: function (fileInfo) {
      this.curFileInfo = fileInfo;
    },
    setCurFolderInfo: function (folderInfo) {
      this.curFolderInfo = folderInfo;
    },
    setContainer(container) {
      curControlledContainer = new FlipDrag(container);
      curContainer = container;
      this.switchSortFunc(this.curSortType, this.curSortOrder);
    },
    sort(fn) {
      this.curFileList.sort(fn);
      this.curFolderList.sort(fn);
    },
    switchSortFunc(type, order) {
      // 根据 type 和 order 生成排序函数
      this.curSortType = type;
      this.curSortOrder = order;
      const sortFunc = this.createSortFunc(type, order);
      this.sort(sortFunc);
    },
    createSortFunc(type, order) {
      let sortFunc;
      switch (type) {
        case SORT_TYPE.DATE:
          sortFunc = (a, b) => {
            const timeStampA = new Date(a[SORT_TYPE.DATE]).valueOf();
            const timeStampB = new Date(b[SORT_TYPE.DATE]).valueOf();
            if (order === SORT_ORDER.ASC) {
              return timeStampA - timeStampB;
            } else if (order === SORT_ORDER.DESC) {
              return timeStampB - timeStampA;
            }
            return 1;
          };
          break;
        case SORT_TYPE.FILE_NAME:
          sortFunc = (a, b) => {
            if (order === SORT_ORDER.ASC) {
              return a[SORT_TYPE.FILE_NAME].localeCompare(
                b[SORT_TYPE.FILE_NAME]
              );
            } else if (order === SORT_ORDER.DESC) {
              return b[SORT_TYPE.FILE_NAME].localeCompare(
                a[SORT_TYPE.FILE_NAME]
              );
            } else {
              return 1;
            }
          };
          break;
      }
      this.curSortFunc = sortFunc;
      return sortFunc;
    },
    toggleGridironPlan(value) {
      this.isGridironPlan = value;
      this.switchSortFunc(this.curSortType, this.curSortOrder);
    },
    flip() {
      if (curControlledContainer) {
        return curControlledContainer.flip();
      }
      return () => {};
    },
    // 判断文件夹还是文件
    checkIsFolder(fileInfo) {
      return !!(
        (fileInfo.folder_id || fileInfo.folder_id === 0) &&
        !fileInfo.file_id &&
        fileInfo.file_id !== 0 &&
        (fileInfo.user_id || fileInfo.user_id === 0)
      );
    },
    // 判断文件还是文件夹
    checkIsFile(fileInfo) {
      return fileInfo.id;
    },
    downloadFile(url) {
      xhr.send();
    },

    down: async function (fileInfo) {
      const that = this;
      const xhr = new XMLHttpRequest();
      xhr.open('GET', fileInfo.data, true);
      xhr.responseType = 'blob';

      xhr.onprogress = function (event) {
        that.setTotal(((event.loaded / event.total) * 100).toFixed(2));
        if (event.loaded === event.total) {
          that.setTotal(0);
        }
      };
      xhr.onload = function () {
        if (xhr.status === 200) {
          const blob = new Blob([xhr.response]);
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = fileInfo.name; // 设定下载文件名
          link.click();
        }
      };
      xhr.send();
    },
    downloadFile: async function (fileInfo) {
      const userInfoStore = useUserInfoStore();
      const toastStore = useToastStore();
      const i18nStore = useI18nStore();
      if (!fileInfo.url) return false;
      if (fileInfo.isSmall) {
        const res = await downloadPoints({ id: fileInfo.id });
        this.down({ ...res, name: fileInfo.name });
        return;
      } else {
        const res = await downloadBigPoints({
          id: fileInfo.id
        });
        if (res.code !== 0) {
          toastStore.showToast({
            severity: 'error',
            summary: 'Error Message',
            detail: i18nStore.translate(
              'insufficient_download_remaining_please_recharge_to_download'
            )
          });
        } else {
          this.down({ ...res, name: fileInfo.name });
        }
      }
    },
    onUploader: async function (file) {
      const userInfoStore = useUserInfoStore();
      const toastStore = useToastStore();
      const i18nStore = useI18nStore();

      // 判断大小文件  小文件
      if (this.Type === 2) {
        // 判断是否超过360M文件 不超过
        if (file.size <= 377487360) {
          // 判断当前文件大小是否小于用户当前可上传大小 当前用户100M
          if (
            file.size <= userInfoStore.userInfo.fileWalletDTO.smallFileMaxSize
          ) {
            // 上传
            uploadFile(file);
            return;
          } else {
            // 如果超出 提醒升级或购买空间
            toastStore.showToast({
              severity: 'error',
              summary: 'Error Message',
              detail: i18nStore.translate(
                'upgrade_to_free_version_or_buy_advanced_package'
              ),
              life: 999999,
              group: 'upload_failed'
            });
            return;
          }
        } else {
          // 判断是否超过360M文件  否
          // 弹窗提示
          toastStore.showToast({
            severity: 'error',
            summary: 'Error Message',
            detail: i18nStore.translate(
              'small_file_upload_file_size_cannot_exceed_360M'
            ),
            life: 999999,
            group: 'upload_failed'
          });
          return;
        }
      }
      // 如果是大文件
      else {
        if (
          file.size <=
          userInfoStore.userInfo.fileWalletDTO.storageAmount -
            userInfoStore.userInfo.fileWalletDTO.storageUsed
        ) {
          // 上传
          uploadBigFile(file);
          return;
        } else {
          // 如果超出 提醒升级
          toastStore.showToast({
            severity: 'error',
            summary: 'Error Message',
            detail: i18nStore.translate(
              'insufficient_remaining_storage_space_please_upgrade_package_or_purchase_space'
            ),
            life: 999999,
            group: 'upload_failed'
          });
          return;
        }
      }
    }
  }
});
